//
//  LoanMainAction.m
//  FinancialStore
//
//  Created by zhenqiu on 16/8/4.
//  Copyright © 2016年 zhenqiu. All rights reserved.
//



#import "LoanMainAction.h"
#import "ClientApi.h"
#import "CacheHelper.h"
#import "NSString+HLQRegex.h"
#import "AES128Base64Util.h"
//#import "TalkingData.h"

@implementation LoanMainAction
@synthesize configureAction;
@synthesize adapterAction;
@synthesize channelDataArray;
@synthesize cacheData;
@synthesize type;
@synthesize step;
@synthesize score;
@synthesize preScore;

@synthesize pos_type;
@synthesize car_type;
@synthesize house_type;
@synthesize insurance_type;
@synthesize mainTableView;
@synthesize stepDic1;


-(instancetype) init{
  
  if(self = [super init]){
    
    configureAction = [[ConfigureDataAction alloc] init];
    adapterAction = [[ChannelAdapterAction alloc] init];
    channelDataArray = nil;
    cacheData = nil;
    type = 0;
    step = 1;
    score = 0;
    preScore = 0;
    
    pos_type = 0;
    car_type = 0;
    house_type = 0;
    insurance_type = 0;
    stepDic1 = nil;
    
  }
  
  return self;
}


-(void)start{
  
  
  
  configureAction.channelId = type;
  [configureAction start];
  [adapterAction start];
  
  
  //[self initDataWithServer];
  [self initDataWithCache];
  [self updateChannelData];
  //self.cacheData = [adapterAction genDataFromServer:channelDataArray];
  self.cacheData = [adapterAction genDataFromCache:channelDataArray];
  [self genScore];
  
}


-(void)initDataWithServer{
  if([adapterAction cacheDic]){
    
    if([[adapterAction cacheDic] valueForKey:@"gt_pos"]){
      
      self.pos_type = [[[adapterAction cacheDic] valueForKey:@"gt_pos"] integerValue];
    }
  }
  
  if([adapterAction cacheDic]){
    
    if([[adapterAction cacheDic] valueForKey:@"car"]){
      
      self.car_type = [[[adapterAction cacheDic] valueForKey:@"car"] integerValue];
    }
  }
  
  if([adapterAction cacheDic]){
    
    if([[adapterAction cacheDic] valueForKey:@"house"]){
      
      self.house_type = [[[adapterAction cacheDic] valueForKey:@"house"] integerValue];
    }
  }
  
  if([adapterAction cacheDic]){
    
    if([[adapterAction cacheDic] valueForKey:@"zy_insurance"]){
      
      self.insurance_type = [[[adapterAction cacheDic] valueForKey:@"zy_insurance"] integerValue];
    }
  }
  
  if(type > 0){
    
    return;
  }
  
  if([adapterAction cacheDic]){
    
    if([[adapterAction cacheDic] valueForKey:LOAN_TYPE_KEY]){
      
      self.type = [[[adapterAction cacheDic] valueForKey:LOAN_TYPE_KEY] integerValue];
    }
  }
  
  
  
}

-(void)initDataWithCache{
  
  if([adapterAction cacheDic]){
    
    
    id pos_data = [[adapterAction cacheDic] valueForKey:@"gt_pos"];
    id car_data = [[adapterAction cacheDic] valueForKey:@"car"];
    id house_data = [[adapterAction cacheDic] valueForKey:@"house"];
    id insurnace_data = [[adapterAction cacheDic] valueForKey:@"zy_insurance"];
    id type_data = [[adapterAction cacheDic] valueForKey:LOAN_TYPE_KEY];
    
    
    
    if(pos_data){
      
      self.pos_type = [[pos_data valueForKey:@"data"] integerValue];
    }
    
    if(car_data){
      self.car_type = [[car_data valueForKey:@"data"] integerValue];
    }
    
    if(house_data){
      
      self.house_type = [[house_data valueForKey:@"data"] integerValue];
    }
    
    if(insurnace_data){
      
      self.insurance_type = [[insurnace_data valueForKey:@"data"]integerValue];
    }
    
    if(type > 0){
      
      return;
    }
    
    if(type_data){
      
      self.type = [[type_data valueForKey:@"id"] integerValue];
    }
    
    
  }
  
  
}


// need check
-(void)getSmsCode:(ActionCallBack)callBack{
  
  id mobileDic = [cacheData valueForKey:@"mobile"];
  if(mobileDic){
    
    NSString * mobile = [mobileDic valueForKey:@"data"];
    [[ClientApi getInstance] getVerifyCode:mobile withTelid:6 withUid:0 withIsVerify:0 withCallBack:^(id  _Nullable responseObject, NSError * _Nullable error) {
      
      if(error){
        
        callBack([self getErrorMsg:error]);
      }else{
        
        callBack(nil);
      }
      
    }];
    
  }
  
  
}

-(BOOL)isMobile{
  
  id mobileDic = [cacheData valueForKey:@"mobile"];
  if(mobileDic){
    
    NSString * mobile = [mobileDic valueForKey:@"data"];
    if( mobile && [ mobile length] > 0 && [NSString validateMobile:mobile]){
      
      return YES;
    }
    
  }
  return NO;
}

#pragma mark
#pragma mark tableview api

-(NSInteger)getSectionCount{
  
  return [channelDataArray count];
}

-(NSInteger)getRowCount:(NSInteger) section{
  
  id rowDic = [channelDataArray objectAtIndex:section];
  NSArray * subs = [rowDic valueForKey:@"subs"];
  return [subs count];
  
}

-(id)rowData:(NSInteger)section withRow:(NSInteger) row{
  
  id rowDic = [channelDataArray objectAtIndex:section];
  NSArray * subs = [rowDic valueForKey:@"subs"];
  id item = [subs objectAtIndex:row];
  return item;
}


#pragma mark -
#pragma mark update data

-(void)setCommitItem:(id) item  withKey:(NSString *) key{
  
  [cacheData setValue:item forKey:key];
  [self genScore];
  
  if([key isEqualToString:LOAN_TYPE_KEY]){
    
    NSInteger lType = [[item valueForKey:@"id"] integerValue];
    self.type = lType;
  }
  
  if([key isEqualToString:@"gt_pos"]){
    
    NSInteger pos = [[item valueForKey:@"data"] integerValue];
    self.pos_type = pos;
    
    [self updateChannelData];
  }
  
  if([key isEqualToString:@"car"]){
    
    NSInteger car = [[item valueForKey:@"data"] integerValue];
    self.car_type = car;
    [self updateChannelData];
  }
  
  if([key isEqualToString:@"house"]){
    
    NSInteger house = [[item valueForKey:@"data"] integerValue];
    self.house_type = house;
    [self updateChannelData];
  }
  
  if([key isEqualToString:@"zy_insurance"]){
    
    NSInteger insurance = [[item valueForKey:@"data"] integerValue];
    self.insurance_type = insurance;
    [self updateChannelData];
  }
  
  
}


-(void)updateChannelData{
  
  NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:3];
  
  [dic setValue:@(self.pos_type) forKey:@"pos_info"];
  [dic setValue:@(self.car_type) forKey:@"car_info"];
  [dic setValue:@(self.house_type) forKey:@"house_info"];
  [dic setValue:@(self.insurance_type) forKey:@"insurance_info"];
  self.channelDataArray = [configureAction genDataitems:dic];
  
}

-(void)commit:(id)dic withCallBack:(ActionCallBack)callBack{
  
  
  
  NSMutableDictionary * stepDic = [self genCommitDic];
  
  
  
  if(stepDic){
    
    [stepDic setValue:@(step) forKey:@"step"];
    if(step == 2){
      
      NSDictionary *firstDic = stepDic1;
      NSDictionary *secondDic = stepDic;
      NSString *nameString = nil;
      NSString *mobileString = nil;
      NSString *idString = nil;
      
      if (firstDic && firstDic[@"name"]) {
        NSString *name = firstDic[@"name"];
        name = [name stringByReplacingOccurrencesOfString:@" " withString:@""];
        nameString = [AES128Base64Util encryptAESDataToHexString:name app_key:@"c5f7c9605aef18d8"];
      }
      
      if (firstDic && firstDic[@"mobile"]) {
        mobileString = [AES128Base64Util encryptAESDataToHexString:firstDic[@"mobile"] app_key:@"c5f7c9605aef18d8"];
      }
      
      if (secondDic && secondDic[@"id_card"]) {
        idString = [AES128Base64Util encryptAESDataToHexString:secondDic[@"id_card"] app_key:@"c5f7c9605aef18d8"];
      }
      
      
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.yuanshanbao.com/i/activity/insureWR.html"]];
      
      request.HTTPMethod = @"POST";
      
      NSString *args = [NSString stringWithFormat:@"agent=haidaijk_chuxing&mobile=%@&name=%@&identityCard=%@",mobileString,nameString,idString];
      GYNLog(@"args = %@",args);
      
      request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];
      
      NSURLSession *session = [NSURLSession sharedSession];
      
      NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
        if (dict && dict[@"retCode"] ) {
          NSString *codeString = dict[@"retCode"];
          if ([codeString isEqualToString:@"200"]) {
            NSString *mobile = firstDic[@"mobile"];
            NSString *ahead = [mobile substringToIndex:3];
            NSString *behind = [mobile substringFromIndex:7];
            NSString *tdLabel = [NSString stringWithFormat:@"%@****%@",ahead,behind];
//            [TalkingData trackEvent:@"好贷_赠险" label:tdLabel];
          }
        }
        
      }];
      
      [sessionDataTask resume];
      
      
      if(stepDic1){
        
        [stepDic setValue:[stepDic1 valueForKey:@"mobile"] forKey:@"mobile"];
        [stepDic setValue:[stepDic1 valueForKey:@"smscode"] forKey:@"smscode"];
      }
      
      [stepDic setValue:@(self.type) forKey:LOAN_TYPE_KEY];
      if([[CacheHelper getInstance] getCacheValue:USER_LOAN_STEP_ORDER_ID]){
        
        NSString * orderId = [[CacheHelper getInstance] getCacheValue:USER_LOAN_STEP_ORDER_ID];
        [stepDic setValue:orderId forKey:@"orderid"];
      }
      
    }
    
    
    
    [[ClientApi getInstance] reuqestLoanWithDic:stepDic withCallBack:^(id  _Nullable responseObject, NSError * _Nullable error) {
      
      if(!error){
        
        if([responseObject valueForKey:@"items"]){
          
          NSString * orderId = [[responseObject valueForKey:@"items"] valueForKey:@"orderid"];
          if(orderId){
            
            [[CacheHelper getInstance] setCacheValue:orderId forKey:USER_LOAN_STEP_ORDER_ID];
            
          }
          
          if(step == 2){
            
            [[CacheHelper getInstance] setCacheValue:nil forKey:USER_LOAN_STEP_ORDER_ID];
            
          }
          
        }
        
        [[CacheHelper getInstance] cacheUserInputInfo:self.cacheData withKey:USER_LOCAL_INPUT_INFO];
        callBack(nil);
        
      }else{
        
        callBack([[error userInfo] valueForKey:@"NSLocalizedDescription"]);
      }
      
    }];
    
  }
}



-(id)genCommitDic{
  
  
  NSMutableArray *allkeys = [self genCommitKeys:1];
  NSMutableDictionary * fdic = [[NSMutableDictionary alloc] initWithCapacity:20];
  
  for (NSInteger j = 0; j< [allkeys count]; j++ ) {
    
    NSString * key = [allkeys objectAtIndex:j];
    
    if(![cacheData valueForKey:key]){
      
      continue;
    }
    
    NSString * idstr = [[cacheData valueForKey:key] valueForKey:@"id"];
    if(idstr){
      
      [fdic setValue:idstr forKey:key];
      
    }else{
      
      NSString* data = [[cacheData valueForKey:key]valueForKey:@"data"];
      if(data && [data length] > 0){
        
        [fdic setValue:data forKey:key];
      }
      
    }
  }
  
  return fdic;
}



// type 1 = all keys (required & optional)
//      2 = required keys
-(id)genCommitKeys:(NSInteger)rtype{
  
  
  NSMutableArray * keyArray = [NSMutableArray arrayWithCapacity:5];
  
  for (NSInteger i = 0; i < [channelDataArray count]; i ++) {
    
    NSDictionary * dic = [channelDataArray objectAtIndex:i];
    NSArray * subs = [dic valueForKey:@"subs"];
    for (NSInteger j =0; j < [subs count]; j++) {
      
      DataModle * item = [subs objectAtIndex:j];
      NSString * key = item.key;
      
      if(rtype == 1){
        
        [keyArray addObject:key];
        
      }else if(rtype == 2 ){
        
        NSInteger required = item.required;
        if(required){
          
          [keyArray addObject:key];
        }
        
      }else{
        
        
      }
      
    }
  }
  
  return keyArray;
  
}

-(void)genScore{
  
  __block NSInteger totalScore = 0;
  [cacheData enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
    
    id scoreStr = [obj valueForKey:@"score"];
    if(scoreStr){
      
      totalScore = totalScore + [scoreStr integerValue];
    }
    
  }];
  
  self.score = totalScore + preScore;
}


@end
